package edu.utsa.cs.vignette.pdf;

import java.io.IOException;
import java.util.List;

import org.apache.pdfbox.PDFToImage;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.util.PDFImageWriter;
import org.apache.pdfbox.util.PDFMergerUtility;
import org.apache.pdfbox.util.Splitter;

import edu.utsa.cs.vignette.annotations.*;

public class PDF {

	@desc("Accepts a string of paths, then writes a merged document to the result path.")
	public static void MergePDFsAndWrite(String[] pathsToPDFs, String resultPath) throws Exception {
		PDFMergerUtility merger = new PDFMergerUtility();
		
		for (String path: pathsToPDFs) {
			merger.addSource(path);
		}
		
		merger.setDestinationFileName(resultPath);
		merger.mergeDocuments();
	}
	
	@desc("Splits a PDF into chunks of numpages pages.  WARNING: Caller is responsible for calling close() on each element in the returned list.")
	public static List<PDDocument> splitEveryNPages(int numpages, String pathToPDF) throws Exception {
		Splitter splitter = new Splitter();
		
		splitter.setSplitAtPage(numpages);
		PDDocument pdfToSplit = PDDocument.load(pathToPDF);
		
		List<PDDocument> results = splitter.split(pdfToSplit);
		
//		pdfToSplit.close();
		
		return results;
	}
	
	public static PDDocument extractPage(int pageNumFromOne, String pathToPDF) throws Exception {
		List<PDDocument> results = splitEveryNPages(pageNumFromOne, pathToPDF);
		int i=0;
		for (PDDocument doc: results) {
			if (i!=0)
				doc.close();
			++i;
		}
		
		Splitter splitter = new Splitter();
		splitter.setSplitAtPage(pageNumFromOne - 1); // Isolate target page.
		results = splitter.split(results.get(0));
		results.get(0).close();
		return results.get(1);
		
	}

	public static void generatePNG(String pdf, String resultPath) throws Exception {
//		PDFImageWriter imageWriter = new PDFImageWriter();
//		PDDocument document = PDDocument.load(pdf);
//        imageWriter.writeImage(document, "png", "", 1, 1, resultPath);
		String args[] = {"-imageType", "png", "-outputPrefix", resultPath,
				"-startPage", "1", "-endPage", "1", pdf};
		PDFToImage.main(args);
	}
	
	

}
